package cn.json.construcor;

import cn.hutool.json.JSONObject;
import cn.json.annotation.Statement;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @Author SHANGGUAN
 **/
public class StatementConstructor {

    /**
     * 到 Bean 对象
     *
     * @param source 源
     * @param clazz 对象class
     * @return {@link T }
     */
    @SneakyThrows
    public static <T> T toBeanObject(JSONObject source, Class<T> clazz) {
        Object entity = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            //如果是final修饰的字段就跳过
            if (Modifier.isFinal(field.getModifiers())) continue;
            //开启private
            field.setAccessible(true);
            Statement annotation = field.getAnnotation(Statement.class);
            if (annotation != null) {
                Object value = annotation.type().getValue(annotation, source);
                field.set(entity, value);
                continue;
            }
            String name = field.getName();
            String o = source.get(name, String.class);
            field.set(entity, o);
        }
        return (T) entity;
    }
}
